<template>
  <BaseDialog
    :visible="visible"
    title="视频播放"
    width="80%"
    footer-type="close"
    :before-close="handleClose"
    @close="$emit('close')"
    @cancel="$emit('close')"
    @confirm="handleClose"
  >
    <div class="stream-player-dialog">
      <!-- 播放器选择 -->
      <div class="player-controls">
        <div class="stream-type-selector">
          <el-radio-group v-model="selectedStreamType" @change="handleStreamTypeChange">
            <el-radio-button label="flv">默认码流</el-radio-button>
            <el-radio-button label="flvsub">网络码流</el-radio-button>
            <!-- <el-radio-button label="hlssub">HLS子码流</el-radio-button>
            <el-radio-button label="hls">HLS主码流</el-radio-button> -->
          </el-radio-group>
        </div>
        
        <div class="player-actions">
          <el-button type="primary" @click="startPlay">
            <el-icon><VideoPlay /></el-icon>
            开始播放
          </el-button>
          <el-button @click="stopPlay">
            <el-icon><VideoPause /></el-icon>
            停止播放
          </el-button>
          <el-button @click="refreshStream">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 视频播放区域 -->
      <div class="video-container">
        <div v-if="!currentStreamUrl" class="no-stream">
          <el-empty description="请选择播放模式并开始播放" />
        </div>
        
        <div v-else class="video-player">
          <!-- 使用封装的VideoPlayer组件 -->
          <VideoPlayer
            ref="videoPlayerRef"
            :video-url="currentStreamUrl"
            :width="'100%'"
            :height="'100%'"
            :autoplay="true"
            :muted="true"
            :controls="false"
            @stream-stats-update="onStreamStatsUpdate"
          />
        </div>
      </div>

      <!-- 流信息 -->
      <div class="stream-info">
        <el-descriptions title="流信息" :column="2" border>
          <el-descriptions-item label="摄像机名称">{{ cameraData?.name || '--' }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ cameraData?.ip || '--' }}</el-descriptions-item>
          <el-descriptions-item label="当前模式">{{ getStreamTypeName(selectedStreamType) }}</el-descriptions-item>
          <el-descriptions-item label="流地址">
            <el-text v-if="currentStreamUrl" type="primary" class="stream-url">
              {{ currentStreamUrl }}
            </el-text>
            <el-text v-else type="info">--</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="分辨率">{{ streamStats.resolution || '--' }}</el-descriptions-item>
          <el-descriptions-item label="码率">{{ streamStats.bitrate ? streamStats.bitrate + ' Kbps' : '--' }}</el-descriptions-item>
          <el-descriptions-item label="帧率">{{ streamStats.fps ? streamStats.fps + ' fps' : '--' }}</el-descriptions-item>
          <el-descriptions-item label="缓冲">{{ streamStats.bufferHealth ? streamStats.bufferHealth + 's' : '--' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { ElButton, ElRadioGroup, ElRadioButton, ElIcon, ElEmpty, ElDescriptions, ElDescriptionsItem, ElText } from 'element-plus'
import { VideoPlay, VideoPause, Refresh } from '@element-plus/icons-vue'
import BaseDialog from '@/components/BaseDialog.vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import type { StreamServer, Device } from '@/types'
import { buildStreamUrl } from '@/utils/streamUrl'

// Props
interface Props {
  visible: boolean
  cameraData: Device | null
  serverData: StreamServer | null
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'close': []
}>()

// 响应式数据
const selectedStreamType = ref<'flv' | 'flvsub' | 'hls' | 'hlssub'>('flv')
const currentStreamUrl = ref('')
const videoPlayerRef = ref<InstanceType<typeof VideoPlayer>>()

// 码流统计信息
const streamStats = ref({
  bitrate: 0,
  fps: 0,
  resolution: '',
  bufferHealth: 0
})

// 流类型名称映射
const getStreamTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    flv: 'FLV主码流',
    flvsub: 'FLV子码流',
    hls: 'HLS主码流',
    hlssub: 'HLS子码流'
  }
  return typeMap[type] || type
}

// 构建流地址
const buildStreamUrlLocal = (streamType: string) => {
  if (!props.cameraData || !props.serverData) return ''
  
  return buildStreamUrl(props.cameraData, props.serverData, streamType as 'flv' | 'flvsub' | 'hls' | 'hlssub')
}

// 处理流类型变化
const handleStreamTypeChange = async () => {
  await stopPlay()
  currentStreamUrl.value = buildStreamUrlLocal(selectedStreamType.value)
}

// 开始播放
const startPlay = async () => {
  if (!props.cameraData || !props.serverData) {
    console.error('播放失败: 缺少摄像机数据或服务器数据')
    return
  }
  
  try {
    console.log('开始播放，摄像机数据:', props.cameraData)
    console.log('服务器数据:', props.serverData)
    console.log('选择的流类型:', selectedStreamType.value)
    
    // 先等待DOM更新
    await nextTick()
    
    // 构建流地址
    currentStreamUrl.value = buildStreamUrlLocal(selectedStreamType.value)
    
    console.log('构建的流地址:', currentStreamUrl.value)
    
    if (!currentStreamUrl.value) {
      throw new Error('无法构建流地址')
    }
    
    // 再次等待DOM更新，确保VideoPlayer组件已经渲染
    await nextTick()
    
  } catch (error) {
    console.error('播放失败:', error)
  }
}

// 停止播放
const stopPlay = async () => {
  if (videoPlayerRef.value) {
    await videoPlayerRef.value.stopPlay()
  }
  currentStreamUrl.value = ''
}

// 处理码流统计信息更新
const onStreamStatsUpdate = (stats: any) => {
  streamStats.value = stats
  console.log('码流统计信息更新:', stats)
}

// 刷新流
const refreshStream = async () => {
  console.log('开始刷新流')
  await stopPlay()
  // 等待一段时间确保停止完成
  await new Promise(resolve => setTimeout(resolve, 500))
  await startPlay()
  console.log('刷新流完成')
}

// 关闭对话框
const handleClose = async () => {
  await stopPlay()
  emit('update:visible', false)
  emit('close')
}

// 监听visible变化
watch(() => props.visible, async (newVisible) => {
  if (newVisible) {
    // 弹框打开时，自动开始播放FLV子码流
    console.log('弹框打开，自动开始播放FLV子码流')
    selectedStreamType.value = 'flv'
    await nextTick() // 等待DOM更新
    await startPlay()
  } else {
    await stopPlay()
  }
})
</script>

<style scoped>
.stream-player-dialog {
  display: flex;
  flex-direction: column;
  height: 70vh;
  gap: 20px;
}

.player-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 6px;
}

.stream-type-selector {
  flex: 1;
}

.player-actions {
  display: flex;
  gap: 12px;
}

.video-container {
  flex: 1;
  position: relative;
  background: #000;
  border-radius: 6px;
  overflow: hidden;
}

.no-stream {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.video-player {
  position: relative;
  width: 100%;
  height: 100%;
}

.stream-info {
  flex-shrink: 0;
}

.stream-url {
  word-break: break-all;
  font-family: monospace;
  font-size: 12px;
}

:deep(.el-radio-button__inner) {
  padding: 8px 16px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style>
